package cn.uin.api.exception;

import cn.uin.api.response.Response;
import cn.uin.types.enums.ResponseCode;
import cn.uin.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;

/**
 * @ClassName ExceptionAdvice
 * @Description:全局异常处理
 * @Author: Administrator
 * @CreateDate: 2025/11/7 11:37
 * @Version: 1.0
 */
@Slf4j
@RestControllerAdvice
public class ExceptionAdvice {

	/**
	 * 业务自定义异常
	 * @param e
	 * @param request
	 * @return
	 */
	@ExceptionHandler(AppException.class)
	public Response<String> handleServiceException(AppException e,
	                                         HttpServletRequest request) {
		String requestURI = request.getRequestURI();
		log.error("请求地址{},发生业务自定义异常{}",requestURI,e.getMessage(), e);
		return Response.<String>builder()
				.code(e.getCode())
				.info(e.getInfo())
				.build();
	}

	/**
	 * 拦截错误SQL异常
	 * @param e
	 * @param request
	 * @return
	 */
	@ExceptionHandler(SQLException.class)
	public Response<String> handleBadSqlGrammarException(SQLException e,
	                                             HttpServletRequest request) {
		String requestURI = request.getRequestURI();
		log.error("请求地址'{}',发生数据库异常.", requestURI, e);
		return Response.<String>builder()
				.code(ResponseCode.SQL.getCode())
				.info(ResponseCode.SQL.getInfo())
				.build();
	}

	/**
	 * 未知的运行时异常
	 * @param e
	 * @param request
	 * @return
	 */
	@ExceptionHandler(RuntimeException.class)
	public Response<String> handleRuntimeException(RuntimeException e,
	                                         HttpServletRequest request) {
		String requestURI = request.getRequestURI();
		log.error("请求地址{},发生未知运行异常", requestURI, e);
		return Response.<String>builder()
				.code(ResponseCode.UN_ERROR.getCode())
				.info(ResponseCode.UN_ERROR.getInfo())
				.build();
	}

	/**
	 * 全局异常
	 * @param e
	 * @param request
	 * @return
	 */
	@ExceptionHandler(Exception.class)
	public Response<String> handleException(Exception e,
	                                  HttpServletRequest request){
		String requestURI = request.getRequestURI();
		log.error("请求地址{},发生系统异常",requestURI,e);
		return Response.<String>builder()
				.code(ResponseCode.UN_ERROR.getCode())
				.info(ResponseCode.UN_ERROR.getInfo())
				.build();
	}

}
